/*
 * 
 *  This file is part of Sourceprojects.org Lycia Copyright 2010 noctarius
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 * 
 */
package org.sourceprojects.lycia.test;

import static org.junit.Assert.assertTrue;

import java.io.InputStream;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.Semaphore;

import org.junit.Test;
import org.sourceprojects.lycia.LyciaConfigurator;
import org.sourceprojects.lycia.LyciaParser;
import org.sourceprojects.lycia.LyciaParserFactory;
import org.sourceprojects.lycia.ParserContext;
import org.sourceprojects.lycia.internal.logging.LyciaLoggerWrapper;
import org.sourceprojects.lycia.test.impl.ComplexXPathTagParser;

public class HeavyMultithreaddedParserTestCase {
	private static final LyciaLoggerWrapper LOGGER = LyciaLoggerWrapper
			.getLogger(HeavyMultithreaddedParserTestCase.class);

	private static final int TESTING_THREADS = 100;
	private static final String[] FILENAMES = { "xpathcomplex.xml" };
	private static final String[] EXPECTED = { "Addition: number1 - 10\n" // xpathcomplete.xml
			+ "Addition: number2 - 20\n"
			+ "Substract: number1 - 20\n"
			+ "Substract: number2 - 10\n"
			+ "Multiply: number1 - 10\n"
			+ "Multiply: number2 - 20\n"
			+ "Divide: number1 - 20\n"
			+ "Divide: number2 - 10\n" };

	private volatile Semaphore semaphore = new Semaphore(TESTING_THREADS);

	@Test
	@SuppressWarnings("unchecked")
	public void testComplexeXPathParsing() throws Exception {
		int count = 0;

		final ExecutorService executor = new ScheduledThreadPoolExecutor(
				TESTING_THREADS);

		final LyciaParser<StringBuilder> parser = LyciaParserFactory
				.newInstance(true);
		final LyciaConfigurator<StringBuilder> configurator = parser
				.getConfigurator();

		parser.setValidatingSchema(false);
		configurator.addTagDefinitionParser(new ComplexXPathTagParser());

		try {
			final Future<Boolean>[] threads = new Future[TESTING_THREADS];
			for (int i = 0; i < TESTING_THREADS; i++) {
				semaphore.acquire();
				threads[i] = executor.submit(new ThreadderSchredder(count++,
						parser, semaphore));

				if (count == FILENAMES.length) {
					count = 0;
				}
			}

			semaphore.acquire(TESTING_THREADS);
			for (int i = 0; i < TESTING_THREADS; i++) {
				assertTrue(threads[i].get());
			}
		} finally {
			executor.shutdown();
		}
	}

	@Test
	@SuppressWarnings("unchecked")
	public void testComplexeXPathParsingHalfThreadpoolSize() throws Exception {
		int count = 0;

		final ExecutorService executor = new ScheduledThreadPoolExecutor(
				TESTING_THREADS / 2);

		final LyciaParser<StringBuilder> parser = LyciaParserFactory
				.newInstance(true);
		final LyciaConfigurator<StringBuilder> configurator = parser
				.getConfigurator();

		parser.setValidatingSchema(false);
		configurator.addTagDefinitionParser(new ComplexXPathTagParser());

		try {
			final Future<Boolean>[] threads = new Future[TESTING_THREADS];
			for (int i = 0; i < TESTING_THREADS; i++) {
				semaphore.acquire();
				threads[i] = executor.submit(new ThreadderSchredder(count++,
						parser, semaphore));

				if (count == FILENAMES.length) {
					count = 0;
				}
			}

			semaphore.acquire(TESTING_THREADS);
			for (int i = 0; i < TESTING_THREADS; i++) {
				assertTrue(threads[i].get());
			}
		} finally {
			executor.shutdown();
		}
	}

	@Test
	@SuppressWarnings("unchecked")
	public void testComplexeXPathParsingQuarterThreadpoolSize()
			throws Exception {
		int count = 0;

		final ExecutorService executor = new ScheduledThreadPoolExecutor(
				TESTING_THREADS / 4);

		final LyciaParser<StringBuilder> parser = LyciaParserFactory
				.newInstance(true);
		final LyciaConfigurator<StringBuilder> configurator = parser
				.getConfigurator();

		parser.setValidatingSchema(false);
		configurator.addTagDefinitionParser(new ComplexXPathTagParser());

		try {
			final Future<Boolean>[] threads = new Future[TESTING_THREADS];
			for (int i = 0; i < TESTING_THREADS; i++) {
				semaphore.acquire();
				threads[i] = executor.submit(new ThreadderSchredder(count++,
						parser, semaphore));

				if (count == FILENAMES.length) {
					count = 0;
				}
			}

			semaphore.acquire(TESTING_THREADS);
			for (int i = 0; i < TESTING_THREADS; i++) {
				assertTrue(threads[i].get());
			}
		} finally {
			executor.shutdown();
		}
	}

	private static class ThreadderSchredder implements Callable<Boolean> {
		private final LyciaParser<StringBuilder> parser;
		private final Semaphore semaphore;
		private final int count;

		ThreadderSchredder(final int count,
				final LyciaParser<StringBuilder> parser,
				final Semaphore semaphore) {
			System.out.println("Using file " + FILENAMES[count]);
			this.count = count;
			this.parser = parser;
			this.semaphore = semaphore;
		}

		@Override
		public Boolean call() throws Exception {
			try {
				final InputStream is = getClass().getClassLoader()
						.getResourceAsStream(FILENAMES[count]);

				parser.getParserContext().setContextObject(new StringBuilder());
				parser.parse(is);

				final ParserContext<StringBuilder> parserContext = parser
						.getParserContext();

				final String result = parserContext.getContextObject()
						.toString();
				final boolean ok = EXPECTED[count].equals(result);

				LOGGER.info(result);
				LOGGER.info(ok);
				return ok;
			} finally {
				semaphore.release();
			}
		}
	}
}
